package com.podium.comment.aspect;

import com.podium.auth.entity.LoginUser;
import com.podium.auth.utils.SecurityUtils;
import com.podium.auth.utils.ServletUtils;
import com.podium.comment.AjaxResult;
import com.podium.comment.annotate.PermAuth;
import com.podium.comment.exceptional.BaseException;
import com.podium.web.system.entity.SysUser;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * @author 邵文泽
 * @description 权限注解切面
 * @date 2025/5/8 15:34
 */
@Aspect
@Slf4j
@Component
public class PermAuthAspect {

    @Around("@annotation(permAuth)")
    public Object around(ProceedingJoinPoint joinPoint, PermAuth permAuth) throws Throwable {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = (SysUser) loginUser.getUser();
        if (sysUser == null) {
            HttpServletRequest request = ServletUtils.getRequest();
            if(request == null){
                throw new BaseException("系统异常，请联系管理员！");
            }
            return new AjaxResult<Void>(401, "请求访问：" + request.getRequestURI() + " 认证失败，无法访问系统资源！");
        }
        boolean hasPermission = sysUser.getPermissions().contains(permAuth.value()) || sysUser.getPermissions().contains("**:**:**");
        if (!hasPermission) {
            HttpServletRequest request = ServletUtils.getRequest();
            if(request == null){
                throw new BaseException("系统异常，请联系管理员！");
            }
            return new AjaxResult<Void>(401, "请求访问：" + request.getRequestURI() + " 认证失败，无法访问系统资源！");
        }
        return joinPoint.proceed();
    }

}
